package com.xuzhiguang.lightnat.common.manager;

import com.xuzhiguang.lightnat.common.constant.AttributeKeyConstant;
import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;

public class ProxyChannelManager {

    private static final ConcurrentHashMap<Long, Channel> channelMap = new ConcurrentHashMap<>();

    public static void add(long sessionId, Channel channel) {

        Channel oldChannel = channelMap.put(sessionId, channel);
        if (oldChannel != null) {
            oldChannel.close();
        }
        channel.attr(AttributeKeyConstant.sessionIdKey).set(sessionId);
    }

    public static void remove(Channel channel) {
        Long sessionId = getSessionId(channel);
        if (sessionId != null) {
            channelMap.remove(sessionId);
        }
    }

    public static Long getSessionId(Channel channel) {
        return channel.attr(AttributeKeyConstant.sessionIdKey).get();
    }

    public static Channel get(long sessionId) {
        return channelMap.get(sessionId);
    }

    public static void setTransferId(Channel channel, Long transferId) {
        channel.attr(AttributeKeyConstant.transferIdKey).set(transferId);
    }

    public static Long getTransferId(Channel channel) {
        return channel.attr(AttributeKeyConstant.transferIdKey).get();
    }

    public static void setSyncDisconnect(Channel channel, boolean syncDisconnect) {
        channel.attr(AttributeKeyConstant.syncDisconnectKey).set(syncDisconnect);
    }

    public static Boolean getSyncDisconnect(Channel channel) {
        return channel.attr(AttributeKeyConstant.syncDisconnectKey).get();
    }

    public static void setProxyId(Channel channel, Long proxyId) {
        channel.attr(AttributeKeyConstant.proxyIdKey).set(proxyId);
    }

    public static Long getProxyId(Channel channel) {
        return channel.attr(AttributeKeyConstant.proxyIdKey).get();
    }


    public static ConcurrentHashMap<Long, Channel> getAll() {
        return channelMap;
    }
}
